package com.android.projectsquirrel;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.*;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.database.Cursor;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

public class SurveyPart3 extends Activity {
	String profilename;
	 public static final String TAG = "Project_2_Group_9";
	 String[] data = new String[2];
	 String flag;
	 String savedObservtaion = "";
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.surveypart3);
        Bundle extras = getIntent().getExtras();
        data = extras.getStringArray("data");
        profilename = data[0];
        flag = data[1];
        String[] differentSiteArray = new String[] {"Yes","No"};
        String[]  numberlist = new String[] {"Stayed the same","Increased","Decreased"};
        String[] treeNames = new String[] {"Dont Know","Yes","No"};
        String[] dataSubmissions = new String[]{"Yes","No",};
        String[]  predators= new String[] {"Never","Low(1-2 per week)","Medium(3-4 per week)","High(5+ per week)"};
        String[] dogs = new String[] {"None","Low(1-2 per day)","Medium(3-4 per day)","High(5+ per day)"};
        String[]  foodlist = new String[] {"Never","Seldom","Often","Regularly"};
        String[] items = new String[] {"Single Family","Multiple Family Dwelling ","Highrise Building","Park","Garden","Commer","School","Lot","Cemetery","Farm"};
        
        Spinner differentSiteSpinner = (Spinner)findViewById(R.id.differentSiteSpinner);
        ArrayAdapter<String> differentSite_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, differentSiteArray);
        differentSite_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        differentSiteSpinner.setAdapter(differentSite_adapter);
        differentSiteSpinner.setSelection(1);
        
        Spinner numberSpinner = (Spinner)findViewById(R.id.numberSpinner);
        ArrayAdapter<String> number_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, numberlist);
        differentSite_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        numberSpinner.setAdapter(number_adapter);
        numberSpinner.setSelection(2);
        
        if("Yes".equals(data[1])){
        	populateFields(data[0]);
        }
        
        
     
    	Button squirrelButton = (Button) findViewById(R.id.squirrelIdentify);
    	squirrelButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	Intent myIntent = new Intent(view.getContext(),FoxGrey.class);
                startActivity(myIntent);
            }
    	});
        
    
    Button submitButton = (Button) findViewById(R.id.Button01);
    submitButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
        	Boolean okToProceed = checkForErrorsPart3();
        	if(okToProceed){
//        		if(checkIfExists()){
        			insertData3();
//        			Intent myIntent = new Intent(view.getContext(),Main.class);
        			Intent myIntent = new Intent(view.getContext(),finalpage.class);
                    startActivity(myIntent);		
                    logResults();
//        			}
//        		
        	}
        }
    });
	}
	
	public void populateFields(String name){
		DBAdapterUpdated db = new DBAdapterUpdated(this);
		CharSequence text;
		int i;
		db.open();
		Cursor c = db.getTitle(name);
    	startManagingCursor(c);
    	if(c.moveToFirst()){
    		EditText email  = (EditText)findViewById(R.id.email);
    		if(c.getString(10)!=null){
    			String textValue = c.getString(10);
    			email.setText(textValue);
    		}
    	}
    	c.close();
		db.close();
	}
	
	public void update(){
		DBAdapter_Survey2 dba = new DBAdapter_Survey2(this);
		DatePicker datePicker  = (DatePicker)findViewById(R.id.DatePicker01);
    	TimePicker timePicker = (TimePicker)findViewById(R.id.TimePicker01);
    	EditText editEmail = (EditText)findViewById(R.id.email);
    	EditText editGrayNumber = (EditText)findViewById(R.id.graynumber);
    	EditText editFoxNumber = (EditText)findViewById(R.id.foxnumber);
    	Spinner foodSource = (Spinner)findViewById(R.id.foodSpinner);
    	EditText otherFood = (EditText)findViewById(R.id.foodother);
    	Spinner compareSpinner = (Spinner)findViewById(R.id.numberSpinner);
    	Spinner diffSpinner = (Spinner)findViewById(R.id.differentSiteSpinner);
    	EditText editComments = (EditText)findViewById(R.id.comments);
		 dba.open();
		 dba.updateTitle2(profilename,
			 			Integer.toString(datePicker.getDayOfMonth()),
			 			Integer.toString(datePicker.getMonth()),
			 			Integer.toString(datePicker.getYear()),
			 			Integer.toString(timePicker.getCurrentHour()),
			 			Integer.toString(timePicker.getCurrentMinute()),
//			 			Integer.toString(timePicker.get),//	
			 			"am",
			 			editEmail.getText().toString(),
			 			editGrayNumber.getText().toString(),
			 			editFoxNumber.getText().toString(),
		        		foodSource.getSelectedItemPosition(),
		        		otherFood.getText().toString(),
		        		compareSpinner.getSelectedItemPosition(),
		        		diffSpinner.getSelectedItemPosition(),
		        		editComments.getText().toString()
		        		);
		        		        
		        dba.close();
	}
	
	public Boolean checkIfExists(){
		DBAdapter_Survey2 dba = new DBAdapter_Survey2(this);
		 dba.open();
		 Boolean flag;
		 flag = dba.checkProfile(profilename);
		 return flag;
		 
	}
	public void show(String st){
		Toast t = Toast.makeText(this,st, Toast.LENGTH_LONG);
    	t.show();
	}
	
	public void insertData3(){
			int hour=0;
			int minute=0;
			String ampm="";
	    	DBAdapterUpdated dba = new DBAdapterUpdated(this);
	    	DatePicker datePicker  = (DatePicker)findViewById(R.id.DatePicker01);
	    	TimePicker timePicker = (TimePicker)findViewById(R.id.TimePicker01);
	    	EditText editEmail = (EditText)findViewById(R.id.email);
	    	EditText editGrayNumber = (EditText)findViewById(R.id.graynumber);
	    	EditText editFoxNumber = (EditText)findViewById(R.id.foxnumber);
	    	Spinner compareSpinner = (Spinner)findViewById(R.id.numberSpinner);
	    	Spinner diffSpinner = (Spinner)findViewById(R.id.differentSiteSpinner);
	    	EditText editComments = (EditText)findViewById(R.id.comments);
	    	if(timePicker.getCurrentHour()>12){
	    		hour = timePicker.getCurrentHour()-12;
	    		ampm = "pm";
	    	}
	    	else if(timePicker.getCurrentHour() == 12){
	    		hour = 12;
	    		ampm = "pm";
	    	}
	    	else if(timePicker.getCurrentHour() < 12){
	    		hour = timePicker.getCurrentHour();
	    		ampm = "am";
	    	}
	    	
			 dba.open();
			 Boolean id;
			 boolean ins;
			 	ins = dba.insertSurveyPart3(data[0],
			 			Integer.parseInt(editGrayNumber.getText().toString()),
			 			Integer.parseInt(editFoxNumber.getText().toString()),
			 			datePicker.getDayOfMonth(),
			 			datePicker.getMonth(),
			 			datePicker.getYear(),
			 			hour,
			 			timePicker.getCurrentMinute(),
			 			ampm,
			 			editEmail.getText().toString(),
		        		diffSpinner.getSelectedItemPosition(),
		        		compareSpinner.getSelectedItemPosition(),
		        		editComments.getText().toString()
		        		);
		        		        
		        dba.close();
		}
	
	public void logResults(){
		int id=0;
		 String[] differentSiteArray = new String[] {"Yes","No"};
	        String[]  numberlist = new String[] {"Stayed the same","Increased","Decreased"};
	        String[] treeNames = new String[] {"Dont Know","Yes","No"};
	        String[] dataSubmissions = new String[]{"Yes","No",};
	        String[]  predators= new String[] {"Never","Low(1-2 per week)","Medium(3-4 per week)","High(5+ per week)"};
	        String[] dogs = new String[] {"None","Low(1-2 per day)","Medium(3-4 per day)","High(5+ per day)"};
	        String[]  foodlist = new String[] {"Never","Seldom","Often","Regularly"};
	        String[] items = new String[] {"Single Family","Multiple Family Dwelling ","Highrise Building","Park","Garden","Commer","School","Lot","Cemetery","Farm"};
	    	Context context = getApplicationContext();
	    	String text = "";
	    	String profiles = new String();
	    	DBAdapterUpdated db = new DBAdapterUpdated(this);
	    	db.open();
	    	Cursor c = db.getTitle(profilename);
	    	startManagingCursor(c);
	    	if(c.moveToFirst()){
//	    		for(int i =1;i<35;i++){
	    		profiles = profiles.concat(c.getColumnName(1)+","+"\""+c.getString(1)+"\""+"\n");	
	    		profiles = profiles.concat(c.getColumnName(2)+","+"\""+c.getString(2)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(3)+","+"\""+c.getString(3)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(4)+","+"\""+c.getString(4)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(5)+","+"\""+c.getString(5)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(6)+","+"\""+c.getString(6)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(7)+","+"\""+c.getString(7)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(8)+","+"\""+c.getString(8)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(9)+","+"\""+c.getString(9)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(10)+","+"\""+c.getString(10)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(11)+","+"\""+c.getString(11)+"\""+"\n");
	    		profiles = profiles.concat(c.getColumnName(12)+","+"\""+c.getString(12)+"\""+"\n");
	    		if(c.getString(13)==null){
	    			text = items[0];
		    		profiles = profiles.concat(c.getColumnName(13)+","+"\""+text+"\""+"\n");
	    		}
	    		else{
		    		 id = Integer.parseInt(c.getString(13));
		    		text = items[id];
		    		profiles = profiles.concat(c.getColumnName(13)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(14)==null){
	    			text = treeNames[0];
		    		profiles = profiles.concat(c.getColumnName(14)+","+"\""+text+"\""+"\n");
	    		} else{
		    		 id = Integer.parseInt(c.getString(14));
		    		 text = treeNames[id];
		    		 profiles = profiles.concat(c.getColumnName(14)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(15)==null){
	    			text = treeNames[0];
		    		profiles = profiles.concat(c.getColumnName(15)+","+"\""+text+"\""+"\n");
	    		}else{
		    		 id = Integer.parseInt(c.getString(15));
		    		 text = treeNames[id];
		    		 profiles = profiles.concat(c.getColumnName(15)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(16)==null){
	    			text = treeNames[0];
		    		profiles = profiles.concat(c.getColumnName(16)+","+"\""+text+"\""+"\n");
	    		}else{
		    		 id = Integer.parseInt(c.getString(16));
		    		 text = treeNames[id];
		    		 profiles = profiles.concat(c.getColumnName(16)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(17)==null){
	    			text = treeNames[0];
		    		profiles = profiles.concat(c.getColumnName(17)+","+"\""+text+"\""+"\n");
	    		}else{
		    		 id = Integer.parseInt(c.getString(17));
		    		 text = treeNames[id];
		    		 profiles = profiles.concat(c.getColumnName(17)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(18)==null){
	    			text = treeNames[0];
		    		profiles = profiles.concat(c.getColumnName(18)+","+"\""+text+"\""+"\n");
	    		}else{	    		
		    		 id = Integer.parseInt(c.getString(18));
		    		 text = treeNames[id];
		    		 profiles = profiles.concat(c.getColumnName(18)+","+"\""+text+"\""+"\n");
	    		}
	    		 
	    		 profiles = profiles.concat(c.getColumnName(19)+","+"\""+c.getString(19)+"\""+"\n");
	    		 if(c.getString(20)==null){
		    			text = foodlist[0];
			    		profiles = profiles.concat(c.getColumnName(20)+","+"\""+text+"\""+"\n");
	    		 }else{
		    		 id = Integer.parseInt(c.getString(20));
		    		 text = foodlist[id];
		    		 profiles = profiles.concat(c.getColumnName(20)+","+"\""+text+"\""+"\n");
	    		 }
	    		 if(c.getString(21)==null){
		    			text = foodlist[0];
			    		profiles = profiles.concat(c.getColumnName(21)+","+"\""+text+"\""+"\n");
	    		 }else{	    		 
		    		 id = Integer.parseInt(c.getString(21));
		    		 text = foodlist[id];
		    		 profiles = profiles.concat(c.getColumnName(21)+","+"\""+text+"\""+"\n");
	    		 }
	    		 if(c.getString(22)==null){
		    			text = foodlist[0];
			    		profiles = profiles.concat(c.getColumnName(22)+","+"\""+text+"\""+"\n");
	    		 }else{	    		 
		    		 id = Integer.parseInt(c.getString(22));
		    		 text = foodlist[id];
		    		 profiles = profiles.concat(c.getColumnName(22)+","+"\""+text+"\""+"\n");
	    		 }
	    		 if(c.getString(23)==null){
		    			text = foodlist[0];
			    		profiles = profiles.concat(c.getColumnName(23)+","+"\""+text+"\""+"\n");
	    		 }else{	    		 
		    		 id = Integer.parseInt(c.getString(23));
		    		 text = foodlist[id];
		    		 profiles = profiles.concat(c.getColumnName(23)+","+"\""+text+"\""+"\n");
	    		 }
	    		 if(c.getString(24)==null){
		    			text = foodlist[0];
			    		profiles = profiles.concat(c.getColumnName(24)+","+"\""+text+"\""+"\n");
	    		 }else{	    		 
		    		 id = Integer.parseInt(c.getString(24));
		    		 text = foodlist[id];
		    		 profiles = profiles.concat(c.getColumnName(24)+","+"\""+text+"\""+"\n");
	    		 }	    		 
	    		 
	    		profiles = profiles.concat(c.getColumnName(25)+","+"\""+c.getString(25)+"\""+"\n");
	    		if(c.getString(26)==null){
	    			text = numberlist[0];
		    		profiles = profiles.concat(c.getColumnName(26)+","+"\""+text+"\""+"\n");
	    		}else{
		    		id = Integer.parseInt(c.getString(26));
		    		 text = numberlist[id];
		    		 profiles = profiles.concat(c.getColumnName(26)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(27)==null){
	    			text = dogs[0];
		    		profiles = profiles.concat(c.getColumnName(26)+","+"\""+text+"\""+"\n");
	    		}else{	    		 
		    		 id = Integer.parseInt(c.getString(27));
		    		 text = dogs[id];
		    		 profiles = profiles.concat(c.getColumnName(27)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(28)==null){
	    			text = dogs[0];
		    		profiles = profiles.concat(c.getColumnName(28)+","+"\""+text+"\""+"\n");
	    		}else{	    		
		    		 id = Integer.parseInt(c.getString(28));
		    		 text = dogs[id];
		    		 profiles = profiles.concat(c.getColumnName(28)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(29)==null){
	    			text = predators[0];
		    		profiles = profiles.concat(c.getColumnName(29)+","+"\""+text+"\""+"\n");
	    		}else{	    		
		    		 id = Integer.parseInt(c.getString(29));
		    		 text = predators[id];
		    		 profiles = profiles.concat(c.getColumnName(29)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(30)==null){
	    			text = predators[0];
		    		profiles = profiles.concat(c.getColumnName(30)+","+"\""+text+"\""+"\n");
	    		}else{	    		 
		    		 id = Integer.parseInt(c.getString(30));
		    		 text = predators[id];
		    		 profiles = profiles.concat(c.getColumnName(30)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(31)==null){
	    			text = predators[0];
		    		profiles = profiles.concat(c.getColumnName(29)+","+"\""+text+"\""+"\n");
	    		}else{	    		 
		    		 id = Integer.parseInt(c.getString(31));
		    		 text = predators[id];
		    		 profiles = profiles.concat(c.getColumnName(31)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(32)==null){
	    			text = dataSubmissions[0];
		    		profiles = profiles.concat(c.getColumnName(32)+","+"\""+text+"\""+"\n");
	    		}else{	    		 
		    		 id = Integer.parseInt(c.getString(32));
		    		 text = dataSubmissions[id];
		    		 profiles = profiles.concat(c.getColumnName(32)+","+"\""+text+"\""+"\n");
	    		}
	    		if(c.getString(33)==null){
	    			text = differentSiteArray[0];
		    		profiles = profiles.concat(c.getColumnName(33)+","+"\""+text+"\""+"\n");
	    		}else{
		    		 id = Integer.parseInt(c.getString(33));
		    		 text = differentSiteArray[id];
		    		 profiles = profiles.concat(c.getColumnName(33)+","+"\""+text+"\""+"\n");
	    		}
	    		 
	    		 	    		
	    		profiles = profiles.concat(c.getColumnName(34)+","+"\""+c.getString(34)+"\""+"\n");
		        }
	    	c.close();
	    	db.close();
	    	Log.i(TAG,profiles);
	    	
	    	

		}
	
	public Boolean checkForErrorsPart3(){
		Boolean ok = true;
		String questionNumbers = "";
		EditText checkGraySquirrels = (EditText) findViewById(R.id.graynumber);
		if((checkGraySquirrels.getText().toString()).equals("")){
			questionNumbers = questionNumbers.concat("Question 4.Please enter the number of gray squirrels.\n");
			ok = false;
			
		}
		EditText checkEmail = (EditText) findViewById(R.id.email);
		String email = checkEmail.getText().toString();
		
		String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = email;
		//Make the comparison case-insensitive.
		Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if(matcher.matches()){
		ok = true;
		}
		else{
			ok = false;
			questionNumbers = questionNumbers.concat("Question 4.Please enter a valid email address.\n");
		}

		
		EditText checkfoxSquirrels = (EditText) findViewById(R.id.foxnumber);
		if((checkfoxSquirrels.getText().toString()).equals("")){
			questionNumbers = questionNumbers.concat("Question 4.Please enter the number of fox squirrels.\n");
			ok = false;
			
		}
		
		Spinner checkCompare = (Spinner) findViewById(R.id.numberSpinner);
		if(checkCompare.getSelectedItemPosition()== 5){
			questionNumbers = questionNumbers.concat("Question 6. Please select a value for the squirrel numbers when compared to last year.\n");
			ok = false;
			
		}
		Spinner checkDifferentSite = (Spinner) findViewById(R.id.differentSiteSpinner);
		if(checkDifferentSite.getSelectedItemPosition()== 3){
			questionNumbers = questionNumbers.concat("Question 7. Please select 'Yes' or 'No' based on your previous submissions.\n");
			ok = false;
			
		}
		if(ok == false){
			showAlert(questionNumbers);
		}
		return ok;
	}
	
	public void showAlert(String str){
		 // prepare the alert box
       AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

       // set the message to display
       alertbox.setMessage(str);

       // add a neutral button to the alert box and assign a click listener
       alertbox.setNegativeButton("Ok", new DialogInterface.OnClickListener() {

           // click listener on the alert box
           public void onClick(DialogInterface arg0, int arg1) {
           }
       });

       // show it
       alertbox.show();
	}
	
	 public boolean onCreateOptionsMenu(Menu menu) {
	        boolean supRetVal = super.onCreateOptionsMenu(menu);
	        menu.add(Menu.NONE, 0, Menu.NONE, "Go Home");
	    	//.setIcon(android.R.drawable.);
		return supRetVal;
	}
	
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case 0:
	        	startActivity(new Intent(SurveyPart3.this, Main.class));
	            return true;
	    }
	    return false;
	}

	}

